package com.yict.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ContextUtil implements ApplicationContextAware {

	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		ContextUtil.setACT(ctx);
	}

	private static ApplicationContext applicationContext;

	/**
	 * 设置WebApplicationContext,该值只允许设置一次
	 * 
	 * @param context
	 * @throws Exception
	 */
	public static void setACT(ApplicationContext context) {
		if (applicationContext != null) {
			return;
		}
		ContextUtil.applicationContext = context;
	}

	/**
	 * 根据Bean的名称取得相应的对象
	 * 
	 * @param beanName
	 * @return
	 * @throws Exception
	 */
	public static Object getBeanObject(String beanName) {
		if (applicationContext == null) {
			throw new RuntimeException("错误:不能获得Bean对象,ApplicationContext没有设置");
		}
		return applicationContext.getBean(beanName);
	}
}
